<?php
$serverBase = dirname($_SERVER['REQUEST_URI']);

if(!isset($_GET['device_code']) || !isset($_GET['APP_CODE']))
{
	$oAuth_req = $serverBase . "/oAuth_req.php";
	echo "<code>APP_CODE and Device-Code is necessary for polling.";
	echo "<br/>Open <a href='$oAuth_req'>OAuth_req.php</a> to begin</code>";
	die;
}

$url = "https://oauth.campus.rwth-aachen.de/oauth2waitress/oauth2.svc/token";

$parameter = array(
	//'scope' => 'l2p.rwth',
	'grant_type' => 'device',
	'code' => $_GET['device_code'],
	'client_id' => $_GET['APP_CODE']
);

$opts = array(
	CURLOPT_SSL_VERIFYPEER => FALSE,
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
	
	CURLOPT_URL => $url,
	CURLOPT_POSTFIELDS => http_build_query( $parameter),
	CURLOPT_POST => TRUE,
	
	CURLOPT_HEADER => TRUE
);

$ch = curl_init();
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);

//$time = 3600;
//$result = '{"error":"authorization pending"}';
//$result = '{"status":"ok","access_token":"WwKlX","expires_in":'.$time.',"refresh_token":null,"token_type":"bearer"}';
echo '<pre>';
	print_r($result);
echo '</pre>';

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);

curl_close($ch);
$token= json_decode($body, true);
echo "<br/>Continue to <a href='$serverBase/oAuth_api_call.php?access_token={$token['access_token']}'>api.call</a>";
?>